/*
   Copyright (c) 2023 李伟国
   learner-platform is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2. 
   You may obtain a copy of Mulan PSL v2 at:
               http://license.coscl.org.cn/MulanPSL2 
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
*/

package cn.platform.controller;

import cn.platform.response.ResponseData;
import cn.platform.response.SuccessResponseData;
import cn.platform.service.IFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping(value = "file")
public class FileController {
    private final static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private IFileService fileService;

    @RequestMapping(value = "image/{filename}", method = RequestMethod.GET)
    public void getImage(@PathVariable("filename") String filename, HttpServletResponse response){
        // 跨域操作
        response.addHeader("Access-Allow-Control-Origin","*");
        response.addHeader("Content-type","application/x-www-form-urlencoded");
        String filePath = fileService.findFilePath(filename);
        if(filePath == null){
            return;
        }
        String suffix = filename.substring(filename.lastIndexOf(".")).replaceAll("\\.","");
        response.setContentType("image/"+suffix);
        try (
                FileInputStream fis = new FileInputStream(filePath);
                ServletOutputStream os = response.getOutputStream();
                ){
            byte[] buffer = new byte[1024];
            int b = 0;
            while((b=fis.read(buffer))!=-1){
                os.write(buffer,0,b);
            }
        }catch (IOException e){
            e.getStackTrace();
            logger.error("图片响应失败");
        }
    }

    @RequestMapping(value = "image", method = RequestMethod.POST)
    public ResponseData uploadImage(MultipartFile file){
        return new SuccessResponseData(fileService.saveImageFile(file));
    }
}
